const { app, BrowserWindow, Menu } = require("electron");

const createWindow = () => {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    show: false,
    title: "自定义菜单",
    webPreferences: {
      nodeIntegration: true, // 允许在渲染线程使用nodejs
      contextIsolation: false, // 上下文隔离
      enableRemoteModule: true // 启用远程模块
    }
  });

  // 自定义的菜单
  const menuTemp = [
    { 
      label: "文件",
      submenu: [
        {
          label: "打开文件",
          click() {
            console.log("打开文件");
          }
        },
        {
          label: "打开目录"
        },
        {
          type: "separator"
        },
        {
          label: "关闭文件夹"
        },
        {
          label: "关于",
          role: "about"
        },
      ]
    },
    { label: "编辑" },
    { 
      label: "角色",
      submenu: [ // 默认API
        { label: "复制", role: "copy" },
        { label: "剪切", role: "cut" },
        { label: "黏贴", role: "paste" },
        { label: "最小化", role: "minimize" },
      ]
    },
    {
      label: "多选效果",
      submenu: [
        { label: "选项1", type: "checkbox" },
        { label: "选项2", type: "checkbox" },
        { label: "选项3", type: "checkbox" },
        { type: "separator" },
        { label: "单选1", type: "radio" },
        { label: "单选2", type: "radio" },
      ]
    },
    { label: "窗口", type: "submenu", role: "windowMenu" },
    { 
      label: "其他",
      submenu: [
        {  
          label: "打开",
          icon: "./03-自定义菜单/assets/open.png",
          accelerator: "ctrl + o",
          click() {
            console.log("打开了一个文件");
          }
        }
      ]
    }
  ];

  // 利用上面的模板生成菜单
  const menu = Menu.buildFromTemplate(menuTemp);

  // 将菜单添加到应用中
  Menu.setApplicationMenu(menu);
  
  win.loadFile("./03-自定义菜单/index.html");
  win.on("ready-to-show", () => {
    win.show();
  });
  require('@electron/remote/main').initialize(); // 初始化远程功能
  require("@electron/remote/main").enable(win.webContents);
}
app.whenReady().then(() => {
  createWindow();

  // 如果没有窗口打开则打开一个窗口 
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });

  // 关闭所有窗口时退出应用 
  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit();
  });
});